<?php
/**
 *	description:ZMAXWECHAT 素材管理模型文件
 *  author：min.zhang
 *  Email:zhang19min88@163.com
 *	Url:http://www.zmax99.com
 *  copyright:南宁市程序人软件科技有限责任公司保留所有权利
 *  date:2016-04-28
 *  @license GNU General Public License version 3, or later
 *  check date:2016-05-26
 *  checker :min.zhang
 */
 
defined('_JEXEC') or die('You can not access this file!');
jimport('joomla.application.component.modeladmin');
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/wechat/token.php");
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/wechat/media.php");
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/wechat/news.php");
require_once(JPATH_COMPONENT_ADMINISTRATOR."/libs/db.php");

class zmaxwechatModelMedia extends JModelAdmin
{
	/**
	 * Method to get the record form.
	 *
	 * @param   array      $data        Data for the form.
	 * @param   boolean    $loadData    True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed  A JForm object on success, false on failure
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_zmaxwechat.media', 'media', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form))
		{
			return false;
		}
		return $form;
	}
	
	public function loadFormData()
	{
		//Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_zmaxwechat.edit.media.data',array());
		if (empty($data)) {
			$data = $this->getItem();
		}
		return $data;
	}
	
	public function getItem($pk=null)
	{
		$item = parent::getItem();
		
		
		$news = json_decode($item->content);
		$newsItems = $news->news_item;
		
		for($i = 0 ;$i < count($newsItems) ;$i++)
		{
			$name="new".$i;
			$item->$name = $newsItems[$i];
		}
		
		
		
		return $item;
		
	}
	
	public function save($data)
	{
		$token = new zmaxwechatToken();
		$token = $token->getToken();
		
		$media = new zmaxwechatMedia($token->token);
		
		
		$news = array();
		for($i=0 ;$i<8;$i++)
		{
			$name="new".$i;
			if(isset($data[$name]) && is_array($data[$name]))
			{
				if($data[$name]["title"] && $data[$name]["content"])
				{
					$news[]=$data[$name];
					$article = $data[$name];				
					$result = $media->updateMedia($data["media_id"],$i,$article);
				}
				
			}
		}
		
		$content = new stdclass();
		$content->news_item=$news;
		$content->create_time = JDate::getInstance()->toUnix();
		$content->update_time = JDate::getInstance()->toUnix();
		
		$data["content"] = json_encode($content);
				
		return parent::save($data);
		
	}
}


?>